package cn.com.zero.manager.auth.api.utils;

/**
 * @author guoxin
 * @version 1.0.0
 * @Description
 * @date 2023/2/13 14:20
 */

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * JWT工具类
 */
public class JwtUtil {

    public JwtUtil(Long JWT_TTL, String JWT_KEY) {
        this.JWT_TTL = JWT_TTL;
        this.JWT_KEY = JWT_KEY;
    }

    //有效期为
    public Long JWT_TTL;// 60 * 60 *1000  一个小时
    //设置秘钥明文
    public String JWT_KEY;

    public String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @return
     */
    public String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        return builder.compact();
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @param total token中要刷新总数
     * @return
     */
    public String createJWT(String subject,Integer total) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID(),total);// 设置过期时间
        return builder.compact();
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return
     */
    public String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }

    private JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("sg")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);
    }

    private JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid,Integer total) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer(total.toString())     // 刷新总数
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);
    }

    /**
     * 创建token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public String createJWT(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

    public void main(String[] args) throws Exception {
//        String jwt = createJWT("2123");
        Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyOTY2ZGE3NGYyZGM0ZDAxOGU1OWYwNjBkYmZkMjZhMSIsInN1YiI6IjIiLCJpc3MiOiJzZyIsImlhdCI6MTYzOTk2MjU1MCwiZXhwIjoxNjM5OTY2MTUwfQ.NluqZnyJ0gHz-2wBIari2r3XpPp06UMn4JS2sWHILs0");
        String subject = claims.getSubject();
        System.out.println(subject);
//        System.out.println(claims);
    }

    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    /**
     * 获取jwt创建时间
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public Date createTime(String jwt){
        Claims claims = null;
        try {
            claims = parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims.getIssuedAt();
    }

    /**
     * 比较jwt创建时间与redis存放时间戳对比
     *
     * @param jwt
     * @param redisTime
     * @return
     */
    public boolean compareCreateTime(String jwt,Date redisTime) {
        if(createTime(jwt).compareTo(redisTime)!=0)
            return false;
        return true;
    }

    /**
     * jwt是否过期,没过期是否重新生成新jwt(-1:过期; 0:没过期,不需要重新生成jwt; 1:没过期,需要重新生成jwt)
     *
     * @param jwt
     * @return
     */
    public Integer isExpire(String jwt){
        try {
            Claims claims = parseJWT(jwt);
            Date expiration = claims.getExpiration();
            Date date = new Date();
            if(expiration.compareTo(date)>0){
                if((expiration.getTime()-date.getTime())<600000L){
                    return 1;
                }
                else
                    return 0;
            }
            else
                return -1;
        } catch (Exception e) {
            return -1;
        }
    }

    /**
     * 重新生成jwt
     *
     * @param jwt
     * @return
     */
    public String reCreateJWT(String jwt){
        try {
            Claims claims = parseJWT(jwt);
            int total = Integer.parseInt(claims.getIssuer())-1;
            if(total<0){
                return null;
            }
            String load = claims.getSubject();
            return createJWT(load,total);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取刷新总数
     *
     * @param jwt
     * @return
     */
    public Integer getTotal(String jwt){
        try {
            Claims claims = parseJWT(jwt);
            return Integer.parseInt(claims.getIssuer());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
